/**
 * 音乐播放器
 **/

import {Platform, StyleSheet, Text, View, Image, TouchableHighlight} from 'react-native';
import React, {Component} from 'react';
import Video from "react-native-video";

export default class MusicPlayer extends Component {

    static defaultProps={
        musicList : [],
        position: 0,
    };

    //设置顶部导航栏的内容
    static navigationOptions = ({navigation, screenProps}) => ({
        //左侧标题
        headerTitle: '音乐播放器',
        //设置跳转页面左侧返回箭头后面的文字，默认是上一个页面的标题
        headerBackTitle: null,
        //顶部标题栏的样式
        headerStyle: styles.headerStyle,
        //顶部标题栏文字的样式
        headerTitleStyle: styles.headerTitleStyle,
    });

    constructor(props) {
        super(props);
        this.player = '';
        console.log("list:"+props.musicList+"  position:"+props.position);
        this.state = {
            musicList: props.musicList,
            position: props.position,
            isPlaying: false,
            curTime: 0,
            duration: 0,
            playStateImage: require('../image/ic_play.png'),
        };
    }

    //把秒数转换为时间类型
    formatTime(time) {
        // 71s -> 01:11
        let min = Math.floor(time / 60)
        let second = time - min * 60
        min = min >= 10 ? min : '0' + min
        second = second >= 10 ? second : '0' + second
        return min + ':' + second
    }

    render() {
        return (
            <View style={{height: 50,flexDirection: 'column'}}>
                <View style={{height: 0.2, backgroundColor: 'gray'}} />
                <View style={{
                    height: 50,
                    flex: 1,
                    flexDirection: 'row',
                }}>
                    <View style={styles.songContainer}>
                        <Image
                            source={{uri: this.state.musicList[this.state.position].imageUrl}}
                            style={styles.image}
                        />
                        <View style={styles.textContainer}>
                            <Text style={{
                                fontSize: 14,
                                marginLeft: 5
                            }}> {this.state.musicList[this.state.position].name + "-" +this.state.musicList[this.state.position].singer} </Text>
                            <Text style={{
                                fontSize: 12,
                                marginTop: 4,
                                marginLeft: 6,
                            }}> {this.formatTime(this.state.curTime) + "/" + this.formatTime(this.state.duration)} </Text>
                        </View>
                    </View>

                    <TouchableHighlight style={styles.imagePlayState} underlayColor='#CFCFCF' onPress={() => {
                        //跳转详情页面
                        this.playAction();
                    }}>
                        <View>
                            <Image
                                style={{width: 26, height: 26,}}
                                source={this.state.playStateImage}
                            />
                        </View>
                    </TouchableHighlight>
                </View>

                <Video
                    ref={(ref) => this.player = ref}
                    source={{uri: this.state.musicList[this.state.position].mp3Url}}
                    rate={1.0}
                    volume={1.0}
                    muted={false}
                    paused={!this.state.isPlaying}
                    playWhenInactive={false}
                    playInBackground={false}
                    progressUpdateInterval={500.0}//设置更新频率
                    onLoadStart={this._onLoadStart}
                    onLoad={this._onLoad}
                    onProgress={this._onProgress}
                    onBuffer={this._onBuffer}
                    onEnd={this._onEnd}
                    onError={this._onError}
                />
            </View>
        );
    }

    //加载开始
    _onLoadStart = () => {
        console.log("onloadStart");
    };

    //加载
    _onLoad = (data) => {
        console.log("onload:" + data.duration);
        this.setState({
            isPlaying: true,
            duration: parseInt(data.duration),
            playStateImage: require('../image/ic_pause.png'),
        });
    };

    //进度
    _onProgress = (data) => {
        console.log("onProgress  progress:" + data.currentTime);
        this.setState({
            curTime: parseInt(data.currentTime),
        });
    };

    //缓冲
    _onBuffer = () => {
        console.log("onBuffer");
    };

    //播放结束
    _onEnd = () => {
        console.log("onEnd 下一首:");
        next();
    };

    _onMusicChange(position){
        this.props.onMusicChange(position);
    }

    playMusic(playPos){
        this.setState({
            position : playPos,
        });
    }

    //播放错误
    _onError = () => {
        console.log("onError");
        next();
    };

    next() {
        let curPos = this.state.position + 1;
        if (curPos > this.state.musicList.length) {
            curPos = 0;
        }
        this.setState({
            position : curPos
        });
        //通知其他组件修改
        this._onMusicChange(curPos);
    }

    //播放切换
    playAction() {
        //判断按钮显示什么
        this.state.isPlaying = !this.state.isPlaying;
        if (this.state.isPlaying == true) {
            this.setState({
                playStateImage: require('../image/ic_pause.png')
            })
        } else {
            this.setState({
                playStateImage: require('../image/ic_play.png')
            })
        }
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        height: 50,
    },
    songContainer: {
        flexGrow: 5,
        flexDirection: 'row',
        alignSelf: 'center',
    },
    textContainer: {
        flexDirection: 'column',
    },
    image: {
        width: 40,
        height: 40,
        marginLeft: 10,
    },
    imagePlayState: {
        flexGrow: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    headerStyle: {
        backgroundColor: '#4398ff',
    },
    headerTitleStyle: {
        //标题的文字颜色
        color: 'white',
        //设置标题的大小
        fontSize: 18,
        //居中显示
        alignSelf: 'center',
    },
});
